//base class
export class UIBase {

  constructor(props) {
    this.props = props;
    this.element = null;
    this._listeners = new Map();
  }

  _createElement(htmlstr){
    const div = document.createElement("div");
    div.innerHTML = htmlstr;
    return div.firstElementChild;
  }

  _bindEvent(element){
    throw new Error("must implements _bindEvent");
  }

  _render(){
    throw new Error("must implements _render");
  }

  render(){
    var htmlstr = this._render();
    var newElement = this._createElement(htmlstr);
    if (this.element) {
      this.element.insertAdjacentElement('beforebegin',newElement);
      this.element.remove();
    }
    this.element = newElement;
    this._bindEvent(this.element);
    return newElement;
  }

  bind(selector){
    if (!this.element) {
      this.render();
    }
    document.querySelector(selector).appendChild(this.element);
  }

  on(event,handle){
    const handles = this._listeners.get(event);
    if (handles) {
      handles.push(handle);
    }else {
      this._listeners.set(event,[handle]);
    }
  }

  emit(..argv){
    const event = argv.shift();
    const handles = this._listeners.get(event);
    if (handles) {
      for(let handle of handles){
        handle(...argv);
      }
    }
  }
}
